package com.xbjtech.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.github.pagehelper.PageInfo;
import com.xbjtech.model.Order;
import com.xbjtech.model.OrderExample;
import com.xbjtech.model.OrderExample.Criteria;
import com.xbjtech.model.Seller;
import com.xbjtech.model.SellerExample;
import com.xbjtech.model.User;
import com.xbjtech.service.OrderService;
import com.xbjtech.service.SellerService;
import com.xbjtech.util.Result;

import lombok.extern.slf4j.Slf4j;

@Controller
@RequestMapping("/order")
@Slf4j
public class OrderController {
	
	@Autowired
	OrderService orderService;
	
	@Autowired
	SellerService sellerService;

	@GetMapping("/list")
	public String list(Model model) {
		SellerExample example = new SellerExample();
		com.xbjtech.model.SellerExample.Criteria criteria = example.createCriteria();
		criteria.andDeletedEqualTo(0);
		criteria.andLockedEqualTo(0);
		List<Seller> sellers = sellerService.list(example);
		model.addAttribute("sellers", sellers);
		return "order/list";
	}
	
	@GetMapping("/toadd")
	public String toAddPage(Model model) {
		SellerExample example = new SellerExample();
		com.xbjtech.model.SellerExample.Criteria criteria = example.createCriteria();
		criteria.andDeletedEqualTo(0);
		criteria.andLockedEqualTo(0);
		List<Seller> sellers = sellerService.list(example);
		model.addAttribute("sellers", sellers);
		return "order/add";
	}
	
	@GetMapping("/toedit/{id}")
	public String toEdit(@PathVariable Long id, Model model) {
		Order order = orderService.selectById(id);
		SellerExample example = new SellerExample();
		com.xbjtech.model.SellerExample.Criteria criteria = example.createCriteria();
		criteria.andDeletedEqualTo(0);
		criteria.andLockedEqualTo(0);
		List<Seller> sellers = sellerService.list(example);
		model.addAttribute("sellers", sellers);
		model.addAttribute("order", order);
		return "order/edit";
	}
	
	@RequestMapping("/delete/{id}")
	@ResponseBody
	public Map<String, Object> deleteById(@PathVariable Long id) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			orderService.deleteOrder(id);
			map.put("flag", Boolean.TRUE);
			map.put("message", "删除成功");
		} catch (Exception e) {
			map.put("flag", Boolean.FALSE);
			map.put("message", "删除失败");
		}
		return map;
	}
	
	@PostMapping("/save")
	public String save(Order order, RedirectAttributes redirectAttributes) {
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		log.info("order:--->{}", order);
		try {
			if (null == order.getId()) {
				order.setCreateSource(1);
				order.setCreateUid(user.getId());
				order.setCreateUname(user.getNickname());
				order.setStat(0);
				order.setCreateTime(new Date());
				order.setSellerName(sellerService.selectSellerById(order.getSellerId()).getNickname());
				orderService.insertOrder(order);
			} else {
				order.setSellerName(sellerService.selectSellerById(order.getSellerId()).getNickname());
				orderService.updateOrder(order);
			}
			// 成功
			redirectAttributes.addFlashAttribute("successMessage", "保存成功");
		} catch (Exception e) {
			// 失败
			redirectAttributes.addFlashAttribute("errorMessage", "保存失败");
			log.error("OrderController.save()-->{}", e.getMessage());
		}
		return "redirect:/order/list";
	}
	
	@GetMapping(value = "/page", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Result<Order> page(
			@RequestParam(value = "page", required = false, defaultValue = "1") int page,
			@RequestParam(value = "rows", required = false, defaultValue = "10") int pageSize,
			@RequestParam(value = "orderId", required = false) String orderId,
			@RequestParam(value = "mobile", required = false) String mobile,
			@RequestParam(value = "sellerId", required = false) Long sellerId,
			@DateTimeFormat(pattern = "yyyy-MM-dd")
			@RequestParam(value = "beginTime", required = false) Date beginTime,
			@DateTimeFormat(pattern = "yyyy-MM-dd")
			@RequestParam(value = "endTime", required = false) Date endTime
			) {
		OrderExample example = new OrderExample();
		example.setOrderByClause("id desc");
		Criteria criteria = example.createCriteria();
		if (orderId != null && !orderId.trim().equals("")) {
			criteria.andAjOrderIdLike("%" + orderId + "%");
		}
		if (mobile != null && !mobile.trim().equals("")) {
			criteria.andBuyerMobileEqualTo(mobile);
		}
		if (sellerId != null) {
			criteria.andSellerIdEqualTo(sellerId);
		}
		if (null != beginTime) {
			criteria.andCreateTimeGreaterThanOrEqualTo(beginTime);
		}
		if (null != endTime) {
			criteria.andCreateTimeLessThan(new Date(endTime.getTime() + 24 * 60 * 60 * 1000));
		}
		
		
		
		
		List<Order> list = orderService.list(example, page, pageSize);
		PageInfo<Order> info = new PageInfo<Order>(list);
		Result<Order> result = new Result<Order>();
		result.setRows(info.getList());
		result.setTotal(info.getTotal());
		return result;
	}
	
}
